<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="com.hnas.core.util.PropertyUtil"%>
<%@page import="com.hnas.core.dto.DataBean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>红包配置信息</title>
<style>
	.td_coupon_count{
		width:10px;
	}
	.td_coupon_period{
		width:10px;
	}
	.tbl_couponConfigure｛
		width:300px;
	｝
</style>
<script type="text/javascript">
</script>
</head>
<body>
	<!-- 标题 -->
	<div class="titleBar m_b_20">
		<div class="tit fl b_l_e74a5f">
			<h3 class="cn">红包配置信息</h3>
			<span class="en">redpacket configure information</span>
		</div>
		<div class="fr"></div>
	</div>
	<!-- end 标题 -->

	<form method="post" action="${pageContext.request.contextPath }/backend/redpacket_configure/search" name="searchForm"  >
  	<input type="hidden" name="pageNo" value="${dto.pageNo}">
  	<input type="hidden" name="totalCount" value="${dto.totalCount}">
	<!-- 查询 -->
	<div class="box_03 p_20 m_b_20">
		<table class="tb_style02" width="100%">
	        <tr>
	            <th>每页显示</th>
	            <td colspan="5">
	            	<input style="width:50px;" class="input_style2" type="text" placeholder="" id="pageSize" name="pageSize" value="${dto.pageSize}"> 条
	                <span style="margin-left:170px;">
	                	<input style="width:110px;" class="btn_brown02 m_r_12" type="button" name="searchData" id="searchData" value="查  询">
	               		<input style="width:110px;" class="btn_brown02 m_r_12" type="button" name="addData" id="addData" value="添 加">
	                </span>
	            </td>
	         </tr>
		</table>
	</div>
	<!-- end 查询 -->
				
</form>

<div class="m_b_20">
	<table class="tb_style05" width="100%" style="table-layout:fixed;">
		<thead>
		<tr>
			<c:forEach items="${beans}" var="o">
			<c:if test="${o.display && !o.hidden}"><th>${o.title}</th></c:if>
			</c:forEach>
			<th width="200">操作</th>
		</tr>
		</thead>
		<tbody>
			<c:forEach items="${pg.list}" var="o">
			<tr>
				<c:forEach items="${beans}" var="o1">
					<c:if test="${o1.display && !o1.hidden}">
					<td style="word-wrap:break-word;"><%=String.valueOf(PropertyUtil.getValue(pageContext.getAttribute("o"),((DataBean)pageContext.getAttribute("o1")).getField())).replace("false","否").replace("true","是")%></td></c:if>
				</c:forEach>
					<td>
						<a href="#" class="c_3366cc btn editData" id="${o.id }">编辑</a>&nbsp;&nbsp;
						<c:if test="${o.valid=='0' }"><a href="#" class="c_3366cc btn enableData" id="${o.id }">启用</a>&nbsp;&nbsp;</c:if>
						<c:if test="${o.valid=='1' }"><a href="#" class="c_3366cc btn disableData" id="${o.id }">禁用</a>&nbsp;&nbsp;</c:if>
						<a href="#" class="c_3366cc btn deleteData" id="${o.id }">删除</a>
					</td>
			</tr>
			</c:forEach>
		</tbody>
	</table>
	<div class="searpage" align="right"><div>${pg.pageStr}</div></div><br/>
</div>
<!-- 添加start -->
<div class="editDataDiv" id="editDIV" title="配置红包规则" style="display: none;" >
	<form action="#" id="editFm" method="post" name="editFm" class="editFm" >
		<input type="hidden" id="dealId" name = "id" value=""/>
		<label>红包规则配置：</label>
		<table >
			<tr>
 				<td width="100px;" align="right"> 
 					<label>配置名称：</label>
 				</td>
 				<td><input type="text" id="configureNameInput" name="configureName" style="width:100px;" />
 				<font color="red"> *</font></td> 
 				<td width="100px;" align="right"> 
 					<label>配置生效时间：</label>
 				</td>
 				<td><input type="text" style="width:80px;" name="startTime" id="startTime" value="" class="input_style2"/><font color="red"> *</font>
  			</tr>
  			<tr>
 				<td width="100px;" align="right"> 
 					<label>红包个数：</label>
 				</td>
 				<td><input type="text" id="couponCountInput" name="couponCount" style="width:100px;"/>个
 				<font color="red"> *</font>
 				</td> 
 				<td width="100px;" align="right"> 
 					<label>最低消费金额：</label>
 				</td>
 				<td><input type="text" id="minAmountInput" name="minAmountStr" style="width:100px;">元
 				<font color="red"> *</font></td> 
  			</tr>
  			<tr>
 				<td width="100px;" align="right"> 
 					<label>红包有效期：</label>
 				</td>
 				<td><input type="text" id="validDateInput" name="validDateStr" style="width:100px;">天
 				<font color="red"> *</font></td> 
 				<td width="100px;" align="right"> 
 					<label>订单笔数限制：</label>
 				</td>
 				<td><input type="text" id="orderNumInput" name="orderNum" rows="3" style="width:100px;" />笔<font color="red"> *</font></td> 
  			</tr>
		</table>
		<label>----------------------------------------------------------------------------------------------------------------------</label><br>
  		<label>代金券规则配置：</label><input type="button" id="addCouponConfigure" value="  +   " />（单击添加代金券类型配置）<label style="float:right;margin-right:25px;">元</label><label id="totalAmount" style="float:right;">0</label><label style="float:right;">优惠总金额：</label>
		<table style="width:420px;margin-left:70px;" id="tbl_couponConfigure">
			<tr>
				<th width="width:30px;">移除</th>
 				<th width="width:130px;">代金券类型</th>
 				<th width="width:130px;">代金券个数</th>
 				<th width="width:130px;">代金券有效期</th>
  			</tr>
		</table>
		
	</form>
</div>
<!-- 添加end -->
<script>
	function FloatAdd(arg1,arg2){
	    var r1,r2,m;
	    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
	    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
	    m=Math.pow(10,Math.max(r1,r2));
	    return (arg1*m+arg2*m)/m;
	}
	//浮点数减法运算
	function FloatSub(arg1,arg2){
	    var r1,r2,m,n;
	    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
	    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
	    m=Math.pow(10,Math.max(r1,r2));
	    //动态控制精度长度
	    n=(r1=r2)?r1:r2;
	    return ((arg1*m-arg2*m)/m).toFixed(n);
	}
	
	//浮点数乘法运算
	function FloatMul(arg1,arg2)
	{
	    var m=0,s1=arg1.toString(),s2=arg2.toString();
	    try{m+=s1.split(".")[1].length}catch(e){}
	    try{m+=s2.split(".")[1].length}catch(e){}
	    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
	}
	
	
	 //浮点数除法运算
	function FloatDiv(arg1,arg2){
	    var t1=0,t2=0,r1,r2;
	    try{t1=arg1.toString().split(".")[1].length}catch(e){}
	    try{t2=arg2.toString().split(".")[1].length}catch(e){}
	    with(Math){
	        r1=Number(arg1.toString().replace(".",""));
	        r2=Number(arg2.toString().replace(".",""));
	        return (r1/r2)*pow(10,t2-t1);
	    }
	}
	function caculateAmount(){
		var totalAmount = 0;
		$(".tr_coupon").each(function(){
			var count = $(this).children("td:eq(2)").children("input:eq(0)").val();
			var price = parseFloat($(this).children("td:eq(1)").children("select:eq(0)").children("option:selected").attr("discountAmount")/100).toFixed(2);
			console.log(count,price,FloatMul(count,price));
			totalAmount = FloatAdd(FloatMul(count,price),totalAmount);
		});
		$("#totalAmount").text(totalAmount);
	}
	function selectChange(obj){
		caculateAmount();
	}
	function couponCountInputBlur(obj){
		//判断必须输入整数
		var count = $(obj).val();
		if(count == null || $.trim(count) == ''){
			$.dialog.alert({title:"错误",content:"代金券个数不能为空！"});
			return false;
		}else{
			var patrn = /^[1-9]\d*|0$/;
            if (!patrn.exec(count)) {
                    $.dialog.alert({title:"错误",content:"代金券个数必须是非负整数！"});
    				return false;
            }
		}
		caculateAmount();
	}
	function couponDateInputBlur(obj){
		//判断必须输入整数
		var count = $(obj).val();
		if(count == null || $.trim(count) == ''){
			$.dialog.alert({title:"错误",content:"有效期不能为空！"});
			return false;
		}else{
			var patrn = /^[1-9]\d*$/;
            if (!patrn.exec(count)) {
                    $.dialog.alert({title:"错误",content:"有效期必须是正整数！"});
    				return false;
            }
		}
		caculateAmount();
	}
	function rmTr(obj){
		$(obj).parent().parent().remove();
		caculateAmount();
	}
	function gotoJumpPage(){
		var jumpNum= $("#jumpNum").val();
		$("#search_page_size").val($("#id_page_size").val());
		gotoPage(jumpNum);
		return false;
	}
	$(function(){
		$("#startTime").datepicker({
			dateFormat:'yy-mm-dd',
			changeYear: true,
			changeMonth: true,
			yearRange: "1900:2049" 
		});
		$("#searchData").click(function(){
			/** 校验输入页数是否非法  **/
			var pageSize=$("#pageSize").val();
			var reg = new RegExp("^[0-9]*$");
			if($.trim(pageSize)!=""){
				if(!reg.test($.trim(pageSize))){
					alert("每页显示数请输入非负整数");
	 				return false;
				}
			}
			if($.trim(pageSize)==""){
				alert("每页显示数不应许为空");
				return false;
			}
			doSubmit();
		});
		//启用
		$(".enableData").click(function(){
			var id = $(this).attr("id");
			var obj = $(this);
			var editURL = "${pageContext.request.contextPath }/backend/redpacket_configure/enable/" + id;
			$.ajax({
				url:editURL,
				type: 'POST',
				error: function(XMLHttpRequest, textStatus, errorThrown){
					 $.dialog.alert({title:"修改",content:"启用失败"});
				},
				success: function(data){
					//改成启用
					query();
				}
			});
		});
		$(".disableData").click(function(){
			var id = $(this).attr("id");
			var obj = $(this);
			var editURL = "${pageContext.request.contextPath }/backend/redpacket_configure/disable/" + id;
			$.ajax({
				url:editURL,
				type: 'POST',
				error: function(XMLHttpRequest, textStatus, errorThrown){
					 $.dialog.alert({title:"修改",content:"启用失败"});
				},
				success: function(data){
					//改成启用
					query();
				}
			});
		});
		//启用
		$(".deleteData").click(function(){
			var id = $(this).attr("id");
			var obj = $(this);
			var editURL = "${pageContext.request.contextPath }/backend/redpacket_configure/delete/" + id;
			$.ajax({
				url:editURL,
				type: 'POST',
				error: function(XMLHttpRequest, textStatus, errorThrown){
					 $.dialog.alert({title:"修改",content:"删除失败"});
				},
				success: function(data){
					//改成启用
					query();
				}
			});
		});
		
		/** 添加 **/	 
		$("#addData").click(function(){
			doReset(document.editFm);
			$("#editDIV").dialog("open");
		});

		/** 编辑 **/
		$(".editData").click(function(){
			var id = $(this).attr("id");
			var editURL = "${pageContext.request.contextPath }/backend/redpacket_configure/show/" + id;
			$.ajax({
				url:editURL,
				type: 'POST',
				error: function(XMLHttpRequest, textStatus, errorThrown){
					//alert('加载数据异常。' + textStatus + "/" + errorThrown);
					 $.dialog.alert({title:"保存",content:"加载数据异常。"});
				},
				success: function(data){
					fillDIV(data);
				}
			});
			$("#editDIV").dialog("open");
		});
		$("#editDIV").dialog({
			autoOpen : false,
			bgiframe: true, 
			height : 500,
			width : 520,
			modal : true,
			resizable :false,
	       	hide: '',
	        show:'',
	        zIndex:1000,
			buttons : {
				"保 存" : function() {
					var bValid = doValid();
					if(bValid){
						var isAdd = ($("#dealId").val() == null) || ($.trim($("#dealId").val()) == "")||($.trim($("#dealId").val()) == "0");
						var myAddUrl = "${pageContext.request.contextPath }/backend/redpacket_configure/add";
						var mySaveUrl = "${pageContext.request.contextPath }/backend/redpacket_configure/save";
						var url = "";
						if(isAdd){
							url= myAddUrl ;
						}else{
							url = mySaveUrl+"/"+$.trim($("#dealId").val());
						}
						var dataObj = {};
						//构造表单提交参数
						//构造红包配置参数
						dataObj.redpacketConfigureName = $("#configureNameInput").val();//配置名称
						dataObj.couponCount = $("#couponCountInput").val();//红包个数
						dataObj.minAmount = $("#minAmountInput").val();//最低消费金额
						dataObj.validDate = $("#validDateInput").val();//红包有效期
						dataObj.orderNumLimit = $("#orderNumInput").val();//订单笔数限制
						dataObj.validBeginTime = $("#startTime").val();//配置生效时间
						//构造代金券配置参数
						var couponTypeIds = "";
						var counts = "";
						var dates = "";
						$(".tr_coupon").each(function(){
							couponTypeIds += $(this).children("td:eq(1)").children("select:eq(0)").children("option:selected").val()+"|";
							counts += $(this).children("td:eq(2)").children("input:eq(0)").val()+"|";
							dates += $(this).children("td:eq(3)").children("input:eq(0)").val()+"|";
						});
						dataObj.couponTypeIds = couponTypeIds;
						dataObj.counts = counts;
						dataObj.dates = dates;
						$.ajax({
							url:url,
							type: 'POST',
							data: dataObj,
							error: function(XMLHttpRequest, textStatus, errorThrown){
							//alert('保存异常。' + textStatus + "/" + errorThrown);
							 $.dialog.alert({title:"保存",content:"保存异常"});
							},
							success: function(data){
								if(data.result==1) {
									$("#editDIV").dialog("close");
									if (isAdd) {
										//alert('添加成功.');
										 $.dialog.alert({title:"保存",content:"添加成功"});
									}
									else {
										//alert('修改成功.');
										$.dialog.alert({title:"保存",content:"修改成功"});
									}
									query();
								} else {
									$.dialog.alert({title:"保存",content:"保存失败："+ data.errorMessage});	
								}
							}
						});  
					}
				}, 
				"取 消" : function() {
					$(this).dialog("close");			
				}
			},
			close : function() {
				$(this).dialog("close");
			}
		});
		function initSelectTable(){
			$("#tbl_couponConfigure").html("<tr><th width='width:30px;'>移除</th><th width='width:130px;'>代金券类型</th><th width='width:130px;''>代金券个数</th><th width='width:130px;'>代金券有效期</th></tr>");
		}
		function fillDIV(data){
			var rpc = data.rpcDto;
			$("#dealId").val(rpc.id);
			var ccList = data.ccList;
			$("#configureNameInput").val(rpc.configureName);//配置名称
			$("#couponCountInput").val(rpc.couponTotalNum);//红包个数
			$("#minAmountInput").val(rpc.minAmountStr);//最低消费金额
			$("#validDateInput").val(rpc.validDate);//红包有效期
			$("#orderNumInput").val(rpc.orderNumLimit);//订单笔数限制
			$("#startTime").val(rpc.validBeginTime);
			//构造代金券配置参数
			initSelectTable();
			var str = "";
			for(var i = 0; i < ccList.length; i++){
				var cc = ccList[i];
				str +=  "<tr class='tr_coupon'><td style='width:30px;text-align:center;'><input type='button' value='  -  ' onclick='rmTr(this);'></td>"+
						"<td style='width:100px;text-align:center;'><select class='coupon_select' style='width:100px;height:26px;' onchange='selectChange(this);'>";
		 		<c:forEach items='${couponTypeList}' var='o'>
		   			var oid = "${o.id}";
		    		if(oid == cc.couponTypeId){
		    			str += "<option value='${o.id}' selected='selected' discountAmount='${o.discountValue}'>${o.couponTypeName}</option>";
		    		}else{
		    			str += "<option value='${o.id}' discountAmount='${o.discountValue}'>${o.couponTypeName}</option>";
		    		}
		 		</c:forEach>
		 		str += "</select></td><td style='width:100px;text-align:center;'><input type='text' class='count_input' style='width:50px;' value='"+cc.maxCount+"' onblur='couponCountInputBlur(this);'/>个</td> <td style='width:100px;text-align:center;'> <input type='text' class='date_input' style='width:50px;' value='"+cc.validDate+"' onblur='couponDateInputBlur(this);'/>天</td> </tr>";
			}
			$("#tbl_couponConfigure").append(str);
			caculateAmount();
		}
		
		function hasRepeat(ary){
			var nary=ary.sort();
			var flag = false;
			for(var i=0;i<ary.length;i++){
				if (nary[i]==nary[i+1]){
					flag = true;
					break;
				}
			}
			return flag;
		}
		
		function doValid(){
			var configureName = $("#configureNameInput").val();
			if(configureName == null || $.trim(configureName) == ''){
				$.dialog.alert({title:"错误",content:"配置名称不能为空！",objCtrl:"#configureNameInput"});
				return false;
			}
			var startTime = $("#startTime").val();
			if(startTime == null || $.trim(startTime) == ''){
				$.dialog.alert({title:"错误",content:"配置生效时间不能为空！",objCtrl:"#startTime"});
				return false;
			}
			var couponCount = $("#couponCountInput").val();
			if(couponCount == null || $.trim(couponCount) == ''){
				$.dialog.alert({title:"错误",content:"红包个数不能为空！",objCtrl:"#couponCountInput"});
				return false;
			}else{
				var patrn = /^[1-9]\d*$/;
	            if (!patrn.exec(couponCount)) {
	                    $.dialog.alert({title:"错误",content:"红包个数必须是正整数！",objCtrl:"#couponCountInput"});
	    				return false;
	            }
			}
			var minAmount = $("#minAmountInput").val();
			if(minAmount == null || $.trim(minAmount) == ''){
				$.dialog.alert({title:"错误",content:"最低消费金额不能为空！",objCtrl:"#minAmountInput"});
				return false;
			}else{
				var patrn = /^\d+(\.\d+)?$/;
	            if (!patrn.exec(minAmount)) {
	                    $.dialog.alert({title:"错误",content:"最低消费金额必须是数字！",objCtrl:"#minAmountInput"});
	    				return false;
	            }
			}
			var validDate = $("#validDateInput").val();
			if(validDate == null || $.trim(validDate) == ''){
				$.dialog.alert({title:"错误",content:"最红包有效期不能为空！",objCtrl:"#validDateInput"});
				return false;
			}else{
				var patrn = /^[1-9]\d*$/;
	            if (!patrn.exec(validDate)) {
	                    $.dialog.alert({title:"错误",content:"最红包有效期必须是正整数！",objCtrl:"#validDateInput"});
	    				return false;
	            }
			}
			var orderNum = $("#orderNumInput").val();
			if(orderNum == null || $.trim(orderNum) == ''){
				$.dialog.alert({title:"错误",content:"订单笔数限制不能为空！",objCtrl:"#orderNumInput"});
				return false;
			}else{
				var patrn = /^-{0,1}[1-9]\d*$/;
	            if (!patrn.exec(orderNum)) {
	                    $.dialog.alert({title:"错误",content:"订单笔数限制必须是整数！",objCtrl:"#orderNumInput"});
	    				return false;
	            }
			}
			//提交的couponTypeId不能有一样的
			var idArr = new Array();
			$(".tr_coupon").each(function(){
				idArr.push($(this).children("td:eq(1)").children("select:eq(0)").children("option:selected").val());
			});
			if(idArr.length <= 0){
				$.dialog.alert({title:"错误",content:"尚未添加代金券类型配置！"});
				return false;
			}
			var repeat = hasRepeat(idArr);
			if(repeat){
				$.dialog.alert({title:"错误",content:"选择的代金券类型有重复！"});
				return false;
			}
			return true;
		}
		$("#addCouponConfigure").click(function(){
			$("#tbl_couponConfigure").append('<tr class="tr_coupon"><td style="width:30px;text-align:center;"><input type="button" value="  -  " onclick="rmTr(this);"></td>'+
			'<td style="width:100px;text-align:center;"><select class="coupon_select" style="width:100px;height:26px;" onchange="selectChange(this);"><c:forEach items="${couponTypeList}" var="o"><option value="${o.id}" discountAmount="${o.discountValue}">${o.couponTypeName}</option></c:forEach></select></td><td style="width:100px;text-align:center;"><input type="text" class="count_input" style="width:50px;" onblur="couponCountInputBlur(this);"/>个</td> <td style="width:100px;text-align:center;"> <input type="text" class="date_input" style="width:50px;" onblur="couponDateInputBlur(this);"/>天</td> </tr>');
		});
		
	});
</script>
</body>
</html>